<template>
  <!-- 包装指令表表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="870px"
    draggable
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      :inline="true"
    >
      <el-form-item label="包装指令编号" prop="packageCommandCode">
        <el-input
          style="width: 250px"
          v-model="formData.packageCommandCode"
          placeholder="请输入包装指令编号"
        />
      </el-form-item>
      <el-form-item label="包装指令名称" prop="packageCommandName">
        <el-input
          style="width: 250px"
          v-model="formData.packageCommandName"
          placeholder="请输入包装指令名称"
        />
      </el-form-item>
      <el-form-item label="工厂" prop="plantId">
        <el-select
          style="width: 250px"
          @change="plantChange"
          v-model="formData.plantId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in plants"
            :key="item.id"
            :label="item.organizationCode"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用场景" prop="applicableScenarios">
        <el-select
          style="width: 250px"
          multiple
          v-model="formData.applicableScenarios"
          placeholder="请输入适用场景"
          :disabled="formData.id ? true : false"
        >
          <el-option
            v-for="item in dictionaryStore.filterDictList('ApplicableScenario')"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="包装物料" prop="packingMaterialShow">
        <!-- <el-input
          style="width: 250px"
          v-model="formData.packingMaterialId"
          placeholder="请输入包装物料"
          clearable
        /> -->
        <el-autocomplete
          style="width: 250px"
          v-model="formData.packingMaterialShow"
          :fetch-suggestions="queryPackingMaterialSearchAsync"
          placeholder="请输入包装物料"
          @select="handlePackingMaterialSelect"
          clearable
        />
      </el-form-item>
      <el-form-item label="是否有标签" prop="isLabel">
        <el-switch
          v-model="formData.isLabel"
          :active-value="1"
          :inactive-value="0"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form-item>
      <el-form-item label="物料" prop="materialShow">
        <!-- <el-input
          style="width: 250px"
          v-model="formData.materialId"
          placeholder="请输入物料"
          clearable
        /> -->
        <el-autocomplete
          style="width: 250px"
          v-model="formData.materialShow"
          :fetch-suggestions="queryMaterialSearchAsync"
          placeholder="请输入包装物料"
          @select="handleMaterialSelect"
          clearable
        />
      </el-form-item>
      <el-form-item label="包装容量" prop="quantity">
        <el-input-number
          style="width: 250px"
          v-model="formData.quantity"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="是否需要托盘" prop="isPallet">
        <el-switch
          v-model="formData.isPallet"
          :active-value="1"
          :inactive-value="0"
          @click="isPalletChange"
          style="
            --el-switch-on-color: #13ce66;
            --el-switch-off-color: #ff4949;
            width: 650px;
          "
        />
      </el-form-item>
      <el-form-item
        label="托盘物料"
        prop="palletMaterialShow"
        v-if="palletAreaShow"
      >
        <!-- <el-input
          style="width: 250px"
          v-model="formData.palletMaterialId"
          placeholder="请输入托盘物料"
          clearable
        /> -->
        <el-autocomplete
          style="width: 250px"
          v-model="formData.palletMaterialShow"
          :fetch-suggestions="queryPalletMaterialSearchAsync"
          placeholder="请输入包装物料"
          @select="handlePalletMaterialSelect"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="托盘数量"
        prop="palletQuantity"
        v-if="palletAreaShow"
      >
        <el-input-number
          style="width: 250px"
          v-model="formData.palletQuantity"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="formData.remarks"
          style="width: 650px"
          type="textarea"
          :rows="3"
          maxlength="255"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMPACKAGECMDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const checkQuantity = (rule: any, value: any, callback: any) => {
  if (value) {
    if (value > 0) {
      callback();
    } else {
      return callback(new Error("请输入包装容量"));
    }
  } else {
    return callback(new Error("请输入包装容量"));
  }
};

const checkPalletMaterialId = (rule: any, value: any, callback: any) => {
  const isPallet = formData.isPallet;
  if (isPallet == 1) {
    if (value) {
      callback();
    } else {
      return callback(new Error("请选择托盘物料"));
    }
  }
};

const checkPalletQuantity = (rule: any, value: any, callback: any) => {
  const isPallet = formData.isPallet;
  if (isPallet == 1) {
    if (value) {
      if (value > 0) {
        callback();
      } else {
        return callback(new Error("请输入托盘数量"));
      }
    } else {
      return callback(new Error("请输入托盘数量"));
    }
  }
};

const rules = reactive({
  packageCommandCode: [
    { required: true, message: "请输入包装指令编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  packageCommandName: [
    { required: true, message: "请输入包装指令名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请选择工厂", trigger: "blur" }],
  applicableScenarios: [
    { required: true, message: "请选择适用场景", trigger: "blur" },
  ],
  materialShow: [{ required: true, message: "请选择物料", trigger: "blur" }],
  packingMaterialShow: [
    { required: true, message: "请选择包装物料", trigger: "blur" },
  ],
  quantity: [{ validator: checkQuantity, trigger: "change" }],
  palletMaterialShow: [
    { validator: checkPalletMaterialId, trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  palletQuantity: [{ validator: checkPalletQuantity, trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);
let plants = ref([]);
const palletAreaShow = ref(false);

let formData = reactive({
  id: "",
  packageCommandCode: "",
  packageCommandName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  applicableScenario: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  packingMaterialId: "",
  packingMaterialCode: "",
  packingMaterialName: "",
  quantity: 0,
  isLabel: 1,
  isPallet: 0,
  palletMaterialId: "",
  palletMaterialCode: "",
  palletMaterialName: "",
  palletQuantity: 0,
  remarks: "",
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  applicableScenarios: [],
  packingMaterialShow: "",
  materialShow: "",
  palletMaterialShow: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        packageCommandCode,
        packageCommandName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        applicableScenario,
        materialId,
        materialCode,
        materialName,
        packingMaterialId,
        packingMaterialCode,
        packingMaterialName,
        quantity,
        isLabel,
        isPallet,
        palletMaterialId,
        palletMaterialCode,
        palletMaterialName,
        palletQuantity,
        remarks,
        version,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        packageCommandCode,
        packageCommandName,
        organizationId,
        organizationCode,
        organizationName,
        plantId,
        plantCode,
        plantName,
        applicableScenario,
        materialId,
        materialCode,
        materialName,
        packingMaterialId,
        packingMaterialCode,
        packingMaterialName,
        quantity,
        isLabel,
        isPallet,
        palletMaterialId,
        palletMaterialCode,
        palletMaterialName,
        palletQuantity,
        remarks,
        version,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
      if (packingMaterialId) {
        formData.packingMaterialShow =
          packingMaterialCode + " " + packingMaterialName;
      }
      if (materialId) {
        formData.materialShow = materialCode + " " + materialName;
      }
      if (palletMaterialId) {
        formData.palletMaterialShow =
          palletMaterialCode + " " + palletMaterialName;
      }
      if (applicableScenario) {
        formData.applicableScenarios.push(applicableScenario);
      }
      if (isPallet == 1) {
        palletAreaShow.value = true;
      }
    }
  }
);

onMounted(() => {
  getPlants();
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.packageCommandCode = "";
  formData.packageCommandName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.applicableScenario = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.packingMaterialId = "";
  formData.packingMaterialCode = "";
  formData.packingMaterialName = "";
  formData.quantity = 0;
  formData.isLabel = 1;
  formData.isPallet = 0;
  formData.palletMaterialId = "";
  formData.palletMaterialCode = "";
  formData.palletMaterialName = "";
  formData.palletQuantity = 0;
  formData.remarks = "";
  formData.version = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.packingMaterialShow = "";
  formData.materialShow = "";
  formData.palletMaterialShow = "";
  formData.applicableScenarios = [];
  palletAreaShow.value = false;
}

const loading = ref(false);

/** 包装指令表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmpackagecmd/saveForPage",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getPlants() {
  const data = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
}

function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plant.organizationCode;
  formData.plantName = plant.organizationName;
  formData.organizationId = plant.parentId;
}

function isPalletChange() {
  palletAreaShow.value = !palletAreaShow.value;
  if (!palletAreaShow.value) {
    formData.palletMaterialId = "";
    formData.palletMaterialCode = "";
    formData.palletMaterialName = "";
    formData.palletQuantity = 0;
  }
}

async function queryPackingMaterialSearchAsync(
  queryString: string,
  cb: (arg: any) => void
) {
  const filterData = await request({
    url: "/mdm/mdmmaterial/getSelectorList",
    method: "post",
    data: {
      materialCode: queryString,
      materialType: 6,
    },
  });
  const data = createFilter(filterData);
  cb(data);
}

async function queryMaterialSearchAsync(
  queryString: string,
  cb: (arg: any) => void
) {
  const filterData = await request({
    url: "/mdm/mdmmaterial/getSelectorList",
    method: "post",
    data: {
      materialCode: queryString,
      materialTypes: [1, 2, 3, 4, 5, 6],
    },
  });
  const data = createFilter(filterData);
  cb(data);
}

async function queryPalletMaterialSearchAsync(
  queryString: string,
  cb: (arg: any) => void
) {
  const filterData = await request({
    url: "/mdm/mdmmaterial/getSelectorList",
    method: "post",
    data: {
      materialCode: queryString,
      materialTypes: [4, 6],
    },
  });
  const data = createFilter(filterData);
  cb(data);
}

const createFilter = (filterData: any) => {
  const data = [];
  if (filterData && filterData.data) {
    for (let index = 0; index < filterData.data.length; index++) {
      const element = filterData.data[index];
      data.push({
        value: element.materialCode + " " + element.materialName,
        selectVal:
          element.id + "|" + element.materialCode + "|" + element.materialName,
      });
    }
  }
  return data;
};

function handlePackingMaterialSelect(row: any) {
  const splitData = row.selectVal.split("|");
  formData.packingMaterialId = splitData[0];
  formData.packingMaterialCode = splitData[1];
  formData.packingMaterialName = splitData[2];
}

function handleMaterialSelect(row: any) {
  const splitData = row.selectVal.split("|");
  formData.materialId = splitData[0];
  formData.materialCode = splitData[1];
  formData.materialName = splitData[2];
}

function handlePalletMaterialSelect(row: any) {
  const splitData = row.selectVal.split("|");
  formData.palletMaterialId = splitData[0];
  formData.palletMaterialCode = splitData[1];
  formData.palletMaterialName = splitData[2];
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
